<template>
<div>
<!--  导航-->
  <el-breadcrumb separator-class="el-icon-arrow-right">
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    <el-breadcrumb-item>用户管理</el-breadcrumb-item>
  </el-breadcrumb>
<!--  卡片-->
  <el-card>
<!--    搜索-->
    <el-row :gutter="20">
      <el-col :span="7">
<!--        queryInfo.query绑定搜索框关键字-->
        <el-input placeholder="请输入内容" class="input-with-select" v-model="queryInfo.query" clearable @clear="getUserlist">
<!--          @click="getUserlist"点击后重新获取列表  如果搜索框有关键字则会获取关键字  @clear="getUserlist"清空内容后重新获取列表-->
          <el-button slot="append" icon="el-icon-search" @click="getUserlist"></el-button>
        </el-input>
      </el-col>
      <el-col :span="4">
        <el-button type="primary" @click="dialogVisible=true">添加用户</el-button>
      </el-col>
    </el-row>
<!--    列表-->
    <el-table :data="userList" style="width: 100%" border  stripe>
<!--      type="index"表示索引  索引列-->
      <el-table-column type="index" label="#"></el-table-column>
      <el-table-column prop="username" label="姓名"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="mobile" label="电话"></el-table-column>
      <el-table-column prop="role_name" label="角色"></el-table-column>
      <el-table-column prop="mg_state" label="状态">
        <!--slot-scope="scope" 插槽-->
        <template slot-scope="scope">
          <el-switch v-model="scope.row.mg_state" @change="handSwitch(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="190px">
        <template slot-scope="scope">
<!--          编辑-->
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="amendUsersbtn(scope.row.id)"></el-button>
<!--          删除-->
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserByID(scope.row.id)"></el-button>
<!--          提示文字-->
          <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
<!--            分配角色-->
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)"></el-button>
          </el-tooltip>

        </template>
      </el-table-column>
    </el-table>

<!--    分页-->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 3, 4]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>
  </el-card>
<!--  添加用户对话框-->
  <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="60%" @close="dialogVisibleClose">
<!--    内容主题区域-->
    <el-form :model="addruleForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="addruleForm.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="addruleForm.password"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="addruleForm.email"></el-input>
      </el-form-item>
      <el-form-item label="手机" prop="mobile">
        <el-input v-model="addruleForm.mobile"></el-input>
      </el-form-item>
    </el-form>
    <!--      底部-->
    <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addUser">确 定</el-button>
  </span>
  </el-dialog>
<!--  修改用户信息对话框-->
  <el-dialog
      title="修改用户信息"
      :visible.sync="amendUsers"
      width="60%"
      @close="amendFormClose">

<!--    表单-->
    <el-form  :model="amendruleForm" :rules="amendFormRules" ref="amendFormRef" label-width="70px"  >
      <el-form-item label="用户名">
        <el-input v-model="amendruleForm.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="amendruleForm.email"></el-input>
      </el-form-item>
      <el-form-item label="手机" prop="mobile">
        <el-input v-model="amendruleForm.mobile"></el-input>
      </el-form-item>
    </el-form>
<!--    底部-->
    <span slot="footer" class="dialog-footer">
    <el-button @click="amendUsers = false">取 消</el-button>
    <el-button type="primary" @click="updateUser">确 定</el-button>
  </span>
  </el-dialog>
<!--  分配角色对话框-->
  <el-dialog title="分配角色" :visible.sync="allotDialogVisible">
    <p>当前的用户:{{userInfo.username}}</p>
    <p>当前的角色:{{userInfo.role_name}}</p>
    <el-select v-model="rolseValues" placeholder="请选择">
<!--      v-model="value"绑定选出来的id :value="item.value"id-->
      <el-option
          v-for="item in rolesList"
          :key="item.id"
          :label="item.roleName"
          :value="item.id">
      </el-option>
    </el-select>
    <span slot="footer" class="dialog-footer">
    <el-button @click="allotDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
  </span>
  </el-dialog>
</div>
</template>

<script>
export default {
name: "user",
  data() {
    //邮箱的效验规则
    var checkEmail = (rule,value,cb) =>{
      const regEmail = /^\w+@\w+(\.\w+)+$/;
      //如果验证成功
      if (regEmail.test(value)){
        return cb();
      }
      //如果验证错误 直接返回错误
      cb(new Error("邮箱不合法"));
    }
    //手机号的效验规则
    var checkMobile = (rule,value,cb) =>{
      const regMobile = /^1[34578]\d{9}$/;
      if (regMobile.test(value)){
        return  cb();
      }
      cb(new Error("手机号不合法"))
    }
    return {
      //获取列表的参数对象
      queryInfo: {
        //搜索关键字
        query:'',
        //当前页码
        pagenum:1,
        //每页显示条数
        pagesize:2
      },
      //获取出来的数组
      userList:[],
      //页数
      total:0,
    //  添加用户对话框的显示和隐藏 true显示 false隐藏
      dialogVisible:false,
    //  添加用户数据
      addruleForm:{
        username:'',
        password:'',
        email:'',
        mobile:''
      },
    //  添加用户效验规则
      addFormRules:{
        username:[
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 5, max: 10, message: '长度在 5 到 10 个字符', trigger: 'blur' }
        ],
        password:[
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
        ],
        email:[
          { required: true, message: '请输入邮箱', trigger: 'blur' },
        //    自定义效验规则
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile:[
          { required: true, message: '请输入密码', trigger: 'blur' },
        //    自定义效验规则
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
    //  修改用户信息对话框显示和隐藏
      amendUsers:false,
    //修改用户信息数据
      amendruleForm:{
      },
    //修改用户验证规则
      amendFormRules:{
        email:[
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          //    自定义效验规则
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile:[
          { required: true, message: '请输入密码', trigger: 'blur' },
          //    自定义效验规则
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
    //  分配权限对象显示和隐藏
      allotDialogVisible:false,
    //  获取当前用户
      userInfo:{},
      //存储分配角色数据
      rolesList:[],
    //  选出来角色的id
      rolseValues:''
    }
  },
  created() {
  this.getUserlist();
  },
  methods: {
    //或许列表数据
    async getUserlist() {
      //获取列表数据 params
      const {data:res} =await this.$http.get('users',{params:this.queryInfo});
      if (res.meta.status!==200) return this.$message.error(res.meta.msg)
      this.userList = res.data.users;
      this.total = res.data.total;
    },
    //每页显示的条数 newSize后每页的条数
    handleSizeChange(newSize){
      this.queryInfo.pagesize = newSize;
      this.getUserlist();
    },
    //切换页码
    handleCurrentChange(newPage){
      this.queryInfo.pagenum = newPage;
      this.getUserlist()
    },
  //  监听开关状态的改变
  //  cutSwtich传入的row
    async handSwitch(cutSwtich){
      //通过put方法修改数据库的内容  请求路径：users/:uId/state/:type
      const {data:res} =  await this.$http.put(`users/${cutSwtich.id}/state/${cutSwtich.mg_state}`)
      if (res.meta.status!==200){
      //  如果修改失败 但是这时候开关状态已经改变 需要取反改回正常的状态
        cutSwtich.mg_state != cutSwtich.mg_state;
        return this.$message.error("更新开关状态失败");
      }
      this.$message.success("更新状态成功")
    },
    //添加用户表单关闭后清除表单内容
    dialogVisibleClose(){
      this.$refs.addFormRef.resetFields();
    },
  //  添加用户的预校验
    addUser(){
      this.$refs.addFormRef.validate(async vali=>{
        if (!vali) return
      //  成功发起添加用户的网络请求
        const {data:res} = await this.$http.post("users",this.addruleForm);
        if (res.meta.status!==201) return this.$message.error("添加用户失败");
        this.$message.success("添加用户成功");
        //关闭窗口
        this.dialogVisible = false;
      //  重新获取数据列表
        this.getUserlist();
      })
    },
  //  点击弹出修改用户信息
    async amendUsersbtn(id){
      this.amendUsers = true;
      const{data:res} =  await this.$http.get(`users/${id}`);
      if (res.meta.status!==200) return this.$message.error("查询用户信息失败");
      this.amendruleForm = res.data;
    },
  //  点击确定更新用户内容
     updateUser(){
      this.$refs.amendFormRef.validate(async vail=>{
        if (!vail) return ;
        //发起修改用户的数据请求
        const {data:res} = await this.$http.put(`users/${this.amendruleForm.id}`,{
          //给email和mobile赋值
          email:this.amendruleForm.email,
          mobile:this.amendruleForm.mobile
        });
        if (res.meta.status!==200) return this.$message.error("修改用户信息失败");
        //关闭窗口
        this.amendUsers = false;
        //重新加载数据列表
        this.getUserlist();
        this.$message.success("修改用户信息成功");
      })
    },
  //  监听表单关闭后重置表单
    amendFormClose(){
      this.$refs.amendFormRef.resetFields();
    },
    //删除用户
    async removeUserByID(id){
     const removeUser =  await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
       confirmButtonText: '确定',
       cancelButtonText: '取消',
       type: 'warning'
     }).catch(err=>err);
     //err=>err相当于 err=>{return err} 箭头函数本来就会有return 所以不用写return
     // 确认删除返回字符串confirm
      if (removeUser!=='confirm') return this.$message.info("已经取消删除");
      //删除数据
      const {data:res} =  await this.$http.delete(`users/${id}`);
      //admin用户不允许删除
      if (res.meta.status!==200) return this.$message.error("删除用户失败");
      this.$message.success("删除用户成功");
      this.getUserlist();
    },
  //  展示分配权限对话框
    async setRole(userInfo){
      this.userInfo=userInfo;
      const {data:res} = await this.$http.get('roles');
      if (res.meta.status!==200) return this.$message.error("获取失败");
      this.rolesList = res.data;
      this.allotDialogVisible = true;
    },
  //  点击确定按钮 分配角色
    async saveRoleInfo(){
      if (!this.rolseValues){
          this.$message.error("请选择要分配的角色");
      }

      const {data:res} = await this.$http.put(`users/${this.userInfo.id}/role`,{rid:this.rolseValues})

      if (res.meta.status!==200) return this.$message.error("更新角色失败");
      this.$message.success("更新角色成功")
      this.getUserlist();
      this.allotDialogVisible = false
    }
  },
}
</script>

<style scoped>

</style>